package com.agile.leetcode.order.delayqueue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/15 10:10
 */
public class OrderDelay implements Delayed {
    // 订单id
    private String orderId;
    // 超时时间
    private Long timeout;

    public OrderDelay(String orderId, Long timeout) {
        this.orderId = orderId;
        this.timeout = timeout + System.nanoTime();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        // 强转
        OrderDelay orderDelay = (OrderDelay) other;
        long l = getDelay(TimeUnit.NANOSECONDS) - orderDelay.getDelay(TimeUnit.NANOSECONDS);
        return (l == 0) ? 0 : ((l < 0) ? -1 : 1);
    }

    public void print() {
        System.out.println(orderId + "编号的订单要删除啦。。。。");
    }
}
